package cn.edu.pzhu.dao.imp;

import java.util.List;

import org.junit.jupiter.api.Test;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import cn.edu.pzhu.dao.UserInfoDAO;
import cn.edu.pzhu.pojo.UserInfo;
import cn.edu.pzhu.util.DruidUtil;

public class UserInfoDAOImp implements UserInfoDAO {
	
	private JdbcTemplate template = new JdbcTemplate(DruidUtil.getDataSource());

	@Override
	public int insert(UserInfo t) {
		String sql = "insert into userinfo values(?,?,?,?)";
		try {
			return template.update(sql, t.getUsername(),t.getEmail(),t.getGender(),t.getType());
		} catch (Exception e) {
			return -1;
		}
	}

	@Override
	public int update(String key, UserInfo t) {
		String sql = "update userinfo set email=?,gender=?,type=? where username=?";
		try {
			return template.update(sql,t.getEmail(),t.getGender(),t.getType(),key);
		} catch (Exception e) {
			return -1;
		}
	}

	@Override
	public UserInfo selectById(String key) {
		String sql = "select * from userinfo where username=?";
		try {
			return template.queryForObject(sql, new BeanPropertyRowMapper<>(UserInfo.class),key);
		} catch (Exception e) {
			return null;
		}		
	}
	@Test
	public void test() {
		System.out.println(selectById("1"));
	}

	@Override
	public List<UserInfo> selectAll() {
		List<UserInfo> list = null;
		String sql = "select * from userinfo";
		try {
			list = template.query(sql, new BeanPropertyRowMapper<>(UserInfo.class));
		} catch (Exception e) {
			return null;
		}		
		return list;
	}

	@Override
	public int destroy(String username) {
		String sql = "delete from userinfo where username = ?";
		try {
			return template.update(sql,username);
		} catch (Exception e) {
			return -1;
		}	
	}

}
